#!/usr/bin/env bash

#
# http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin
set -e

# delete $CDPATH with value
export -n CDPATH

# is debug mode?
if [ "${1}" = "--debug" ]; then
  export SBTENV_DEBUG=1
  shift
fi

# set debug PS4 prompt
if [ -n "${SBTENV_DEBUG}" ]; then
  export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '
  set -x
fi

READLINK=$(type -p greadlink readlink | head -1)
if [ -z "${READLINK}" ]; then
  echo "sbtenv: cannot find readlink - are you missing GNU coreutils?" >& 2
  exit 1
fi

resolve_link() {
  ${READLINK} "${1}"
}

abs_dirname() {
  local cwd="$(pwd)"
  local path="${1}"
  
  while [ -n "${path}" ]; do
    cd "${path%/*}"
    local name="${path##*/}"
    path="$(resolve_link "${name}" || true)"
  done

  pwd
  cd "${cwd}"
}

# set sbtenv rootdir
if [ -z "${SBTENV_ROOT}" ]; then
  SBTENV_ROOT="${HOME}/.sbtenv"
else
  SBTENV_ROOT="${SBTENV_ROOT%/}"
fi
export SBTENV_ROOT

# set working directory
if [ -z "${SBTENV_DIR}" ]; then
  SBTENV_DIR="$(pwd)"
else
  cd "${SBTENV_DIR}" 2> /dev/null || {
    echo "sbtenv: cannot change working directory to \"${SBTENV_DIR}\""
    exit 1
  } >& 2
  SBTENV_DIR="$(pwd)"
  cd "${OLDPWD}"
fi
export SBTENV_DIR

# enable nullglob
shopt -s nullglob

# export PATH
bin_path="$(abs_dirname "${0}")"
for plugin_bin in "${SBTENV_ROOT}/plugins/"*/bin; do
  bin_path="${bin_path}:${plugin_bin}"
done
export PATH="${bin_path}:${PATH}"

# export hook path
hook_path="${SBTENV_HOOK_PATH}:${SBTENV_ROOT}/sbtenv.d:/usr/local/etc/sbtenv.d:/etn/sbtenv.d:/usr/lib/sbtenv/hooks"
for plugin_hook in "${SBTENV_ROOT}/plugins/"*/etc/sbtenv.d; do
  hook_path="${hook_path}:${plugin_hook}"
done
export SBTENV_HOOK_PATH="${hook_path}"

# disable nullglob
shopt -u nullglob

command="${1}"
case "${command}" in
  "" | "-h" | "--help" )
    echo -e "$(sbtenv-version)\n$(sbtenv-help)" >& 2
    ;;
  "-v" )
    exec sbtenv---version
    ;;
  * )
    command_path="$(command -v "sbtenv-${command}" || true)"
    if [ -z "${command_path}" ]; then
      echo "sbtenv: no such sub-command \"${command}\"" >& 2
      exit 1
    fi
    shift 1
    exec "${command_path}" "${@}"
    ;;
esac

